﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
using HandyControl.Controls;
using MyHelper;
using clf.weighing.entity;
using CheckBox = System.Windows.Controls.CheckBox;
using Button = System.Windows.Controls.Button;
using Size = System.Windows.Size;

namespace weighing
{
    /// <summary>
    /// UserWindow.xaml 用户管理  的交互逻辑
    /// </summary>
    public partial class UserWindow : GlowWindow
    {
        #region variables
        public List<UserVo>? mUserVos = new();
        //当前修改的用户
        private UserVo? mCurrentUser;
        //当前设置角色的用户
        private UserVo? mCurrSetRoleUserVo;
        private bool isEdit = false;
        private bool isSaveing = false;
        private List<Role>? Roles;
        /// <summary>
        /// 已经获取的角色
        /// </summary>
        private List<UserRole>? userRoles;
        private List<CheckBox>? RoleCheckBoxs;
        #endregion

        public UserWindow()
        {
            InitializeComponent();
            CommonFunction.ShowCustomIcon(this);
        }

        private void UserWindow_Loaded(object sender, RoutedEventArgs e)
        {
            mCurrentUser = new UserVo(new User());
        }

        private void UserWindow_ContentRendered(object sender, EventArgs e)
        {
            LoadUserData();
        }

        private void UserWindow_Unloaded(object sender, RoutedEventArgs e)
        {
            mCurrentUser = null;
        }

        private void UserLv_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            var d = this.userLv.SelectedItem as User;
        }

        private void LoadUserData()
        {
            mUserVos = UserDao.Instance.GetUserList()?.Select((i) =>
            {
                return new UserVo(i);
            }).ToList();
            this.userLv.ItemsSource = mUserVos;
        }

        private void EditBtn_Click(object sender, RoutedEventArgs e)
        {
            Button? button = sender as Button;
            this.DrawerHeader.Text = "修改用户";
            mCurrentUser = button?.Tag as UserVo;
            this.AddDrawerRight.IsOpen = true;
            isEdit = true;
            this.nameTb.Text = mCurrentUser?.Name??"";
            this.usernameTb.Text = mCurrentUser.LoginName;
            this.phoneTb.Text = mCurrentUser.Phone;
            this.pwdTb.Visibility = Visibility.Hidden;
        }

        private void DelBtn_Click(object sender, RoutedEventArgs e)
        {
            var button = sender as Button;
            var userVo = button?.Tag as UserVo;
            if (userVo.RoleType == (int)UserRoleType.Developer || userVo.Id == App.CurrentUser?.id)
            {
                CommonFunction.AlertInfo("禁止对该用户执行删除操作！");
                return;
            }
            if (App.CurrentUser.id == userVo.Id)
            {
                CommonFunction.AlertInfo("不能删除自己！");
                return;
            }
            if (App.CurrentUser.roleType < userVo.RoleType)
            {
                CommonFunction.AlertInfo("无权操作！");
                return;
            }
            string msg = $"是否要删除 用户：{userVo.Name}";
            var reault = CommonFunction.Ask(msg ,this);

            if (reault ==  MessageBoxResult.Yes)
            {
                var size = new Size(this.ActualWidth, this.ActualHeight);
               
                var res = UserDao.Instance.DeleteUser(userVo.mUser);

                if (res > 0)
                {
                    this.mUserVos.Remove(userVo);
                    this.userLv.ItemsSource = null;
                    this.userLv.ItemsSource = this.mUserVos;
                    CommonFunction.AlertInfo("操作成功");
                }
                else if (res == -1)
                {
                    CommonFunction.AlertInfo("操作失败：用户已经产生了过磅数据，不能删除！");
                }
                else
                {
                    CommonFunction.AlertInfo("操作失败");
                    Growl.ErrorGlobal("操作失败");
                }
            }
        }

        private void AddUserBtn_Click(object sender, RoutedEventArgs e)
        {
            this.SetRoleCbItemSource();
            this.DrawerHeader.Text = "添加用户";
            this.AddDrawerRight.IsOpen = true;
            this.isEdit = false;
            this.pwdTb.Visibility = Visibility.Visible;
        }

        private void SetRoleCbItemSource()
        {
            if (Roles.IsNullOrEmpty())
            {
                Roles = RoleDao.Instance.AllList();
            }
        }

        /// <summary>
        /// 保存 信息
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void SaveBtn_Click(object sender, RoutedEventArgs e)
        {
            if (isSaveing == true) return;
            isSaveing = true;
            int res;
            if (isEdit)
            {
                res = Update();
            }
            else
            {
                res = Insert();
            }

            if (res > 0)
            {
                isEdit = false;
                Growl.Success("保存成功", "main");
                CommonFunction.AlertInfo("保存成功");
                //重置 
                this.ResertInput();

                LoadUserData();

            }
            else
            {
                this.saveBtn.IsChecked = false;
                HandyControl.Controls.MessageBox.Show("保存失败", "提示", MessageBoxButton.OK, MessageBoxImage.Error);
            }
            this.AddDrawerRight.IsOpen = false;
            isSaveing = false;
        }

        private int Insert()
        {
            if (App.CurrentCompanyVo == null)
            {
                this.saveBtn.IsChecked = false;
                isSaveing = false;
                HandyControl.Controls.MessageBox.Show("系统未初始使用单位。！ ", "提示", MessageBoxButton.OK, MessageBoxImage.Error);
                return 0;
            }

            mCurrentUser.Name = this.nameTb.Text.Trim();
            if (mCurrentUser.Name.IsNullOrEmpty())
            {
                this.saveBtn.IsChecked = false;
                isSaveing = false;
                HandyControl.Controls.MessageBox.Show("用户的真实姓名输入不正确", "错误", MessageBoxButton.OK, MessageBoxImage.Error);
                return 0;
            };

            mCurrentUser.Phone = this.phoneTb.Text.Trim();
            if (!RegexHelper.IsPhoneNumber(mCurrentUser.Phone))
            {
                this.saveBtn.IsChecked = false;
                HandyControl.Controls.MessageBox.Show("手机号输入 不正确", "错误", MessageBoxButton.OK, MessageBoxImage.Error);
                isSaveing = false;
                return 0;
            };
            mCurrentUser.Password = this.pwdTb.Password.Trim();
            if (mCurrentUser.Password.IsNullOrEmpty())
            {
                mCurrentUser.Password = EncryptHelper.MD5Encrypt(App.Config.SystemConfig.DefaultPassword);
            }
            else
            {
                if (mCurrentUser.Password.Length.IsBetween(6, 20))
                {
                    mCurrentUser.Password = EncryptHelper.MD5Encrypt(mCurrentUser.Password);
                }
                else
                {
                    this.saveBtn.IsChecked = false;
                    HandyControl.Controls.MessageBox.Show("密码长度 6 到20 位 ", "错误", MessageBoxButton.OK, MessageBoxImage.Error);
                    isSaveing = false;
                    return 0;
                }
            }

            mCurrentUser.Id = IdHelper.LongID;
            mCurrentUser.LoginName = this.usernameTb.Text.Trim();
            mCurrentUser.Addtime = DateTime.Now;
            mCurrentUser.AddUserId = App.CurrentUser.id;
            mCurrentUser.AddUserName = App.CurrentUser.name;
            mCurrentUser.AffiliatedCompanyId = App.CurrentCompanyVo.Id;
            mCurrentUser.Company = App.CurrentCompanyVo.FullName;
            mCurrentUser.Qq = this.QQTb.Text;
            mCurrentUser.Weichat = this.WeicahtTb.Text;
            mCurrentUser.Email = this.emalTb.Text;
            mCurrentUser.IsDelete = 0;
            mCurrentUser.RoleType = (int)UserRoleType.Weighinger;
            User? oldUser = UserDao.Instance.FindByPhoneOrName(mCurrentUser.Phone, mCurrentUser.Name);

            //存在
            if (oldUser != null)
            {
                //禁用
                if (oldUser.status == 0)
                {
                    HandyControl.Controls.MessageBox.Show("用户已经存在并且被禁用 ", "失败", MessageBoxButton.OK, MessageBoxImage.Information);
                }
                else
                {
                    HandyControl.Controls.MessageBox.Show("用户已经存", "失败", MessageBoxButton.OK, MessageBoxImage.Information);
                }
                this.saveBtn.IsChecked = false;
                isSaveing = false;
                return 0;
            }
            int res = UserDao.Instance.Sqlite.Insert(mCurrentUser.mUser);
            return res;
        }

        private int Update()
        {
            
            mCurrentUser.Name = this.nameTb.Text.Trim();
            if (mCurrentUser.Name.IsNullOrEmpty())
            {
                this.saveBtn.IsChecked = false;
                isSaveing = false;
                HandyControl.Controls.MessageBox.Show("用户的真实姓名输入不正确", "错误", MessageBoxButton.OK, MessageBoxImage.Error);
                return 0;
            };

            mCurrentUser.Phone = this.phoneTb.Text.Trim();
            if (!RegexHelper.IsPhoneNumber(mCurrentUser.Phone))
            {
                this.saveBtn.IsChecked = false;
                HandyControl.Controls.MessageBox.Show("手机号输入 不正确", "错误", MessageBoxButton.OK, MessageBoxImage.Error);
                isSaveing = false;
                return 0;
            };
            mCurrentUser.LoginName = this.usernameTb.Text.Trim();
            mCurrentUser.Qq = this.QQTb.Text;
            mCurrentUser.Weichat = this.WeicahtTb.Text;
            mCurrentUser.Email = this.emalTb.Text;
            return UserDao.Instance.Sqlite.Update(mCurrentUser.mUser);
        }

        /// <summary>
        /// 重置 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void CancelBtn_Click(object sender, RoutedEventArgs e)
        {
            ResertInput();
        }
        //重置 
        private void ResertInput()
        {

            mCurrentUser = new UserVo(new User());
            this.saveBtn.IsChecked = false;
            this.nameTb.Text = "";
            this.phoneTb.Text = "";
            this.usernameTb.Text = "";
            this.pwdTb.Password = "";
            this.QQTb.Text = "";
            this.emalTb.Text = "";
            this.WeicahtTb.Text = "";
        }
        /// <summary>
        /// 导出 EXCL
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void ExportUserBtn_Click(object sender, RoutedEventArgs e)
        {
            CommonFunction.AlertInfo("请稍等....");
        }
        #region 设置角色
        private void SetRoleBtn_Click(object sender, RoutedEventArgs e)
        {
            Button? btn = sender as Button;
            mCurrSetRoleUserVo   = btn?.Tag as UserVo;
            if (mCurrSetRoleUserVo?.Id == 1)
            {
                mCurrSetRoleUserVo = null;
               CommonFunction.AlertInfo("该用户不能操作");
                return;
            }
            this.roleDrawerHeader.Text = $"为 {mCurrSetRoleUserVo?.Name} 设置角色";
            this.RoleDrawer.IsOpen = true;
        }

        //设置角色
        private void SelecrRoleBtn_Click(object sender, RoutedEventArgs e)
        {
            if (userRoles != null)
            {
                int res = UserRoleDao.Instance.Update((long)mCurrSetRoleUserVo.Id, userRoles);
                if (res > 0)
                {
                    this.RoleDrawer.IsOpen = false;
                    CommonFunction.AlertInfo("修改成功");
                    LoadUserData();
                }
                else
                {
                    CommonFunction.AlertInfo("修改失败");
                    this.selectRoleBtn.IsChecked = false;
                }
            }
        }

        private void CancelRoleBtn_Click(object sender, RoutedEventArgs e)
        {
            this.RoleDrawer.IsOpen = false;
        }

        private void RoleDrawer_Opened(object sender, RoutedEventArgs e)
        {
            if (Roles == null || Roles.Count <= 0)
            {
                Roles =RoleDao.Instance.AllList();
            }
            userRoles = UserRoleDao.Instance.GetListByUserId((long)mCurrSetRoleUserVo.Id);
            if (RoleCheckBoxs.IsNullOrEmpty())
            {
                RoleCheckBoxs = new List<CheckBox>();
                var style = FindResource("CheckBoxBaseStyle") as Style;
                for (int i = 0; i < Roles.Count; i++)
                {
                    Role r = Roles[i];
                    var cb = new CheckBox()
                    {
                        Style = style,
                        Content = r.name,
                        IsChecked = false,
                        HorizontalAlignment =System.Windows. HorizontalAlignment.Left,
                        Tag = r,
                        Margin = new Thickness(20, 5, 20, 5),
                    };
                    foreach (var item in userRoles)
                    {
                        if (r.id == item.roleId)
                        {
                            cb.IsChecked = true;
                        }
                    }
                    cb.Checked += RoleCB_Checked;
                    cb.Unchecked += RoleCB_UnChecked;
                    RoleCheckBoxs.Add(cb);
                }
                this.RolePannel.Children.Clear();
                RoleCheckBoxs.ForEach(cb => this.RolePannel.Children.Add(cb));
            }
            for (int i = 0; i < RoleCheckBoxs.Count; i++)
            {
                Role r = Roles[i];
                var cb = RoleCheckBoxs[i];
                for (int j = 0; j < userRoles.Count; j++)
                {
                    var item = userRoles[j];
                    if (r.id == item.roleId)
                    {
                        cb.IsChecked = true;
                    }
                }
            }

        }

        private void RoleCB_UnChecked(object sender, RoutedEventArgs e)
        {
            CheckBox cb = sender as CheckBox;
            Role r = cb.Tag as Role;
            for (int i = 0; i < userRoles.Count; i++)
            {
                if (userRoles[i].roleId == r.id)
                {
                    userRoles.Remove(userRoles[i]);
                }
            }
        }
        //选中
        private void RoleCB_Checked(object sender, RoutedEventArgs e)
        {
            if (userRoles.IsNullOrEmpty())
            {
                userRoles = new List<UserRole>();
            }
            CheckBox cb = sender as CheckBox;
            Role r = cb.Tag as Role;

            UserRole ur = new UserRole()
            {
                id = IdHelper.LongID,
                userId = (long)mCurrSetRoleUserVo.Id,
                roleId = r.id
            };
            bool has = false;
            foreach (var item in userRoles)
            {
                if (item.roleId == r.id) { has = true; }
            }
            if (!has)
            {
                userRoles.Add(ur);
            }
        }
        private void RoleDrawer_Closed(object sender, RoutedEventArgs e)
        {
            this.selectRoleBtn.IsChecked = false;
            RoleCheckBoxs.ForEach((cb) => { cb.IsChecked = false; });
            this.roleDrawerHeader.Text = "设置角色";
            userRoles = null;
            mCurrSetRoleUserVo = null;
        }

        #endregion

        //重置密码
        private void ResetPwd_Click(object sender, RoutedEventArgs e)
        {
            Button? button = sender as Button;
            UserVo? vo = button?.Tag as UserVo;
            string pwd = "123456";
            string msg = $"是否将{vo?.Name} 的密码重置为 {pwd} ";
            var res = CommonFunction.Ask(msg, this);
            if (res == MessageBoxResult.Yes)
            {
                vo.SyncTime = DateTimeHelper.GetTimeStamp();
                vo.Password = EncryptHelper.MD5Encrypt(pwd);
                int r = UserDao.Instance.Sqlite.Update(vo.mUser);
                if (r > 0)
                {
                    Growl.Success("重置成功！");
                }
                else
                {
                    Growl.Clear();
                    Growl.Error("重置失败！");
                }
            }
        }
    }
}
